//
//    Tokaplot
//    https://code.google.com/p/tokaplot/
//
//    License: GPL v3
//    https://code.google.com/p/tokaplot/wiki/License
//
//    This file is part of Tokaplot.
//
//    Tokaplot is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    Tokaplot is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with Tokaplot.  If not, see <http://www.gnu.org/licenses/>
//

package com.tokaplot;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.regex.Pattern;

//import android.util.Log;

// Class for reading CPU information
public class ReadCPULoad {
	
	//private static final String TAG = "Tokaplot";
	
	boolean fileExists = false;
	
	private static Pattern pSpaceSlashSplit = Pattern.compile("\\s+|/");
	
	public ReadCPULoad() {
		
		// Try and open file
		File fCPULoad = new File("//proc//loadavg");
    	if (fCPULoad.exists() == false) {
    		fCPULoad = null;
    		fileExists = false;
    	} else {
    		fileExists = true;
    	}
	}
	
	public boolean canRead() {
		return fileExists;
	}
	
	public boolean read(float [] cpu_val) {
		
 		// CPU load
		File fCPULoad = new File("//proc//loadavg");
    	if (fCPULoad != null && fCPULoad.exists()) {
			try {
				//Read file
			    BufferedReader brCPU = new BufferedReader(new FileReader(fCPULoad), 1000);
			    String line;
			    String [] lineElements;
			    
			    if ((line = brCPU.readLine()) != null) {
			    	lineElements = pSpaceSlashSplit.split(line, 6);
			    	cpu_val[0] = Float.parseFloat(lineElements[0]);
			    	brCPU.close();
			    	return true;
			    }
			    
			    // Can't find CPU load values
			    brCPU.close();
			    fCPULoad = null;
			}
			catch (Exception e) {
				
				// Can't read file
				fCPULoad = null;
			}
    	}
    	return false;
	}
	
}
